<?php


namespace app\unify\model;


use think\db\Query;
use think\Model;

/**
 * 系统配置表
 * @package app\unify\model
 */
class Config extends Base
{

    const SYSTEM_TRUE = 1;
    const SYSTEM_FALSE = 0;

    //显示状态
    const STATUS_ENABLE = 1;
    const STATUS_DISABLE = 0;
    const STATUS_LIST = [
        self::STATUS_ENABLE => '启用',
        self::STATUS_DISABLE => '禁用',
    ];

    const TYPE_INPUT = 'input';
    const TYPE_TEXTAREA = 'textarea';
    const TYPE_ARRAY = 'array';
    const TYPE_SWITCH = 'switch';
    const TYPE_RADIO = 'radio';
    const TYPE_CHECKBOX = 'checkbox';
    const TYPE_SELECT = 'select';
    const TYPE_HIDDEN = 'hidden';
    const TYPE_IMAGE = 'image';
    const TYPE_FILE = 'file';
    const TYPE_DATE = 'date';
    const TYPE_DATETIME = 'datetime';
    const TYPE_TIME = 'time';


    const TYPE_LIST = [
        self::TYPE_INPUT => '单行文本',
        self::TYPE_TEXTAREA => '多行文本',
        self::TYPE_ARRAY => '数组',
        self::TYPE_SWITCH => '开关',
        self::TYPE_RADIO => '单选按钮',
        self::TYPE_CHECKBOX => '多选按钮',
        self::TYPE_SELECT => '下拉框',
        self::TYPE_HIDDEN => '隐藏',
        self::TYPE_IMAGE => '图片',
        self::TYPE_FILE => '文件',
        self::TYPE_DATE => '日期',
        self::TYPE_DATETIME => '日期时间',
        self::TYPE_TIME => '时间'
    ];

    public function __construct(object|array $data = [])
    {
        parent::__construct($data);

        $this->readOnly(array_merge($this->readonly, [
            'id'
        ]));
    }

    public function getTypeNameAttr($value, $data)
    {
        return (self::TYPE_LIST[$data['type']] ?? "-") . "（" . $data['type'] . "）";
    }

    public function getGroupIdAttr($value)
    {
        return strval($value);
    }

    public function getGroupNameAttr($value, $data){
        return ConfigGroup::where([
            [ConfigGroup::getPrimaryKey(), '=', $data['group_id']]
        ])->value("title");
    }


    public function getStatusNameAttr($value, $data){
        return self::STATUS_LIST[$data['status']]??"-";
    }

    public function searchGroupIdAttr(Query $q, $value, $data): void
    {
        $q->where('group_id', '=', $value);
    }

    public function searchNameAttr(Query $q, $value, $data): void
    {
        $q->where('name', '=', $value);
    }

    public function searchStatusAttr(Query $q, $value, $data): void
    {
        if (empty($value)) {
            return;
        }

        $status = self::STATUS_ENABLE;
        if (app()->isDebug() && is_numeric($value)) {
            $status = $value;
        }

        $q->where('status', '=', $status);
    }
}